<template>
  <div ref="chartRef"></div>
</template>

<script setup lang="ts">
import { onMounted, ref, toRefs, UnwrapRef, watch } from 'vue';
import { EChartsInitOpts, echarts, BaseChartExpose } from '../../lib/echarts';
import { EChartsOption } from 'echarts/types/dist/shared';
import { EChartsType } from 'echarts/core';

interface Props {
  /** 图表配置 */
  option: EChartsOption | UnwrapRef<EChartsOption>;
  /** 图表容器初始化配置 */
  echartsInitOpts: EChartsInitOpts;
}

const props = defineProps<Props>();
const chartRef = ref<HTMLElement>();
const { option } = toRefs(props);
let chartInstance: EChartsType | null = null;

function getEchartsInstance() {
  return chartInstance;
}

/**
 * 对外暴露属性
 */
defineExpose<BaseChartExpose>({
  getEchartsInstance,
});

onMounted(() => {
  // 创建图表
  chartInstance = echarts.init(
    chartRef.value as HTMLElement,
    undefined,
    props.echartsInitOpts
  );
  chartInstance.setOption(props.option as EChartsOption);
});

// 更新图表
watch(
  option,
  () => {
    chartInstance?.setOption(props.option as EChartsOption);
  },
  {
    deep: true,
  }
);
</script>
